package cn.com.huzo.service.tech.impl;

import cn.com.huzo.model.entities.tech.CostForecastHeaderEntity;

import huzofw.model.entities.paginator.Paginator;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.com.huzo.repository.tech.CostForecastHeaderRepository;
import cn.com.huzo.repository.tech.CostForecastLinesPictureRepository;
import cn.com.huzo.repository.tech.CostForecastLinesRepository;
import cn.com.huzo.service.tech.CostForecastHeaderManager;
import org.apache.commons.collections4.MapUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 产品成本预测明细表管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("CostForecastHeaderManager")
public class CostForecastHeaderManagerImpl extends GenericManagerImpl<CostForecastHeaderEntity, Long>
        implements CostForecastHeaderManager {

    @Resource(name = "CostForecastHeaderRepository")
    private CostForecastHeaderRepository _dao;

    @Resource(name = "CostForecastLinesRepository")
    private CostForecastLinesRepository _dao_lines;
    
    @Resource(name = "CostForecastLinesPictureRepository")
    private CostForecastLinesPictureRepository _dao_lines_picture;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchByHeaderKey(Long headerId, Long currentUserId, Long workFlowId) throws Exception {
        Map<String, Object> _result = new HashMap();

        _result.put("HeaderEntity", _dao.fetchByKey(headerId, currentUserId, workFlowId));
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(headerId));
        _result.put("PictureList", _dao_lines_picture.fetchAll(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();
        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<CostForecastHeaderEntity> itemList = _dao.fetchForPage(criterion);
            Paginator<CostForecastHeaderEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     */
    @Override
    @Transactional
    public Map<String, Object> add(CostForecastHeaderEntity instance) throws Exception {
        Map<String, Object> _result = new HashMap();
        Long key = _dao.insert(instance);
        if (key != null && key > 0 && instance.getBomHeaderId() != 0) {
            // 根据款号（从单耗选定）生成成本预测表明细记录
            _dao_lines.insertLinesByBom(key, instance.getBomHeaderId(), instance.getPerColourQuantity());

            // 审计日志
            writeAuditLog(instance.getUpdatedBy(), "技术管理→成本预测", "款号：" + instance.getStyleNo(), "增加成本预测");
        }

        _result.put("HeaderEntity", _dao.fetchByKey(key, instance.getUpdatedBy(), instance.getWorkFlowId()));
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(key));
        _result.put("PictureList", _dao_lines_picture.fetchAll(key));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Integer update(CostForecastHeaderEntity instance) throws Exception {
        Integer rowsAffected = _dao.update(instance);

        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(instance.getUpdatedBy(), "技术管理→成本预测", "款号：" + instance.getStyleNo(), "更新成本预测");
        }

        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        // 删除
        Integer rowsAffected = _dao.delete(MapUtils.getLong(criterion, "HeaderId"));

        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"), "技术管理→成本预测",
                    "票号：" + MapUtils.getString(criterion, "DeletedBillNo"), "删除成本预测");
        }
        return fetchForPage(criterion);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public String fetchNewBillNo() throws Exception {
        return _dao.fetchNewBillNo();
    }
}
